package com.huangmingfu;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

/**
 * @Author: 黄名富
 * @Description: Jdk 动态代理
 */
public class JdkDynamicProxy {

    private interface Subject {
        void request(String source,String token);
    }

    private static class RealRequest implements Subject{

        @Override
        public void request(String source, String token) {
            System.out.println("请求网络");
        }
    }

    private static class RequestIntercept implements InvocationHandler {

        private final Subject subject;

        private RequestIntercept(Subject subject) {
            this.subject = subject;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("请求参数:" + Arrays.asList(args));
            Object result = method.invoke(subject, args);
            System.out.println("记录访问日志");
            return result;
        }
    }

    public static void main(String[] args) {
        Subject realSubject = new RealRequest();
        Subject subject = (Subject) Proxy.newProxyInstance(JdkDynamicProxy.class.getClassLoader(), new Class[]{Subject.class}, new RequestIntercept(realSubject));
        subject.request("小程序","1344");
    }

}
